package cn.zyjblogs.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * copyright (C), 2020, 北京同创永益科技发展有限公司
 *
 * @author zhuyijun
 * @version 1.0.0
 * <author>              <time>                 <version>                   <description>
 * zhuyijun         2020/11/12 15:23             1.0
 * @program springcloud
 * @description
 * @create 2020/11/12 15:23
 */
@Component
public class DynamicRoutingFilter  extends ZuulFilter{
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER +3;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("DynamicRoutingFilter执行了");
        //1、获取Request对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //2、获取参数，redisKey
        String redisKey = request.getParameter("redisKey");

        //3、直接判断
        if (redisKey != null && redisKey.equalsIgnoreCase("customer")) {
            System.out.println("DynamicRoutingFilter执行了路由到了/customer");
            //http://localhost:8080/customer
            context.put(FilterConstants.SERVICE_ID_KEY,"customer-v1");
            context.put(FilterConstants.REQUEST_URI_KEY,"/customer");
        } else if (redisKey != null && redisKey.equalsIgnoreCase("search")) {
            System.out.println("DynamicRoutingFilter执行了路由到了/search/1");
            //http://localhost:8081/search
            context.put(FilterConstants.SERVICE_ID_KEY,"search");
            context.put(FilterConstants.REQUEST_URI_KEY,"/search/1");
        }
        return null;
    }
}
